package com.company.lagou.homework.homework2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {

    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket s = null;
        BufferedReader br = null;
        PrintStream ps = null;

        try {
            //创建ServerScoket类型的对象并提供端口号
            ss = new ServerSocket(8888);
            //等待客户端的连接请求，调用accept方法
            System.out.println("等待客户端连接请求");
            s = ss.accept();
            System.out.println("客户端连接成功");

            //使用输入输出流进行通信
            //实现客户端发来字符串内容的接收并打印
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            //当没有数据发来时，下面的方法会形成阻塞
            String s1 = br.readLine();
            System.out.println("客户端发来的字符串内容是：" + s1);
            //实现服务器向客户端回发字符串的接收并打印"I recieved"
            ps = new PrintStream(s.getOutputStream());
            ps.println("I received");
            System.out.println("客户端发送数据成功！");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭Scoket并释放有关的资源
            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ss) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
